package action;

import Impl.FriendDaoImpl;
import entity.Friend;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "FriendAction")
public class FriendAction extends HttpServlet {
    FriendDaoImpl friendDao =new FriendDaoImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("-------正在执行FriendAction---------");
        request.setCharacterEncoding("utf-8");
//        获取登录用户的用户名
        HttpSession session = request.getSession();
        String uname = (String) session.getAttribute("uname");
        FriendDaoImpl friendDao = new FriendDaoImpl();
        String method =request.getParameter("method");
        List<Friend> friends = new ArrayList<>();
//        如果是按照姓名查询
        if (method!=null && method.equals("find")){
            System.out.println("-------正在按照姓名查询单个好友！----------");
            String fname = request.getParameter("findFriend");
            System.out.println(fname);
            friends = friendDao.findFriendByName(uname, fname);
            request.setAttribute("page", "no");
        } else{
            System.out.println("--------正在从查询所有好友信息！--------");
            int pageNow = 0;
            if(request.getParameter("pageNow") == null) {
                pageNow = 1;
                System.out.println(pageNow);
            }else {
                pageNow = Integer.parseInt(request.getParameter("pageNow"));
            }
            //       获取该用户所有的好友信息
            List<Friend> friendList =friendDao.findAllfriend(uname);

            int allcount = friendList.size();
            System.out.println(allcount);
            int allpage;
            if(allcount % 5 == 0){
                allpage=allcount / 5;
            }
            else{
                allpage=allcount / 5 + 1;
            }
            System.out.println(allpage);
            friends=friendDao.findFriendsByPage(uname,pageNow);
            request.setAttribute("allpage", allpage);
            request.setAttribute("pageNow", pageNow);
        }
        request.setAttribute("friend_info",friends);
        request.getRequestDispatcher("/friend.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
